const { contextBridge, ipcRenderer } = require("electron");

/**
 * 截断过长的链接，显示开头和结尾
 * @param {string} url - 要截断的URL
 * @param {number} maxLength - 最大长度，默认80
 * @returns {string} 截断后的URL
 */
function truncateUrl(url, maxLength = 80) {
  if (url.length <= maxLength) {
    return url;
  }

  const startLength = Math.floor(maxLength * 0.4); // 开头占40%
  const endLength = Math.floor(maxLength * 0.4); // 结尾占40%

  const start = url.substring(0, startLength);
  const end = url.substring(url.length - endLength);

  return `${start}...${end}`;
}

/**
 * 检测是否为下载链接
 * @param {string} url - 要检查的URL
 * @param {HTMLElement} element - 链接元素
 * @returns {boolean} 是否为下载链接
 */
function isDownloadLink(url, element) {
  const downloadUrl = new URL(url);

  // 检查是否有download属性
  if (element && element.hasAttribute("download")) {
    return true;
  }

  // 检查URL是否包含常见的下载文件扩展名
  const downloadExtensions = [
    ".pdf",
    ".doc",
    ".docx",
    ".xls",
    ".xlsx",
    ".ppt",
    ".pptx",
    ".zip",
    ".rar",
    ".7z",
    ".tar",
    ".gz",
    ".mp3",
    ".mp4",
    ".avi",
    ".mov",
    ".wmv",
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".bmp",
    ".svg",
    ".txt",
    ".csv",
    ".json",
    ".xml",
  ];

  const pathname = downloadUrl.pathname.toLowerCase();
  return downloadExtensions.some((ext) => pathname.endsWith(ext));
}

function getMimeTypeByExtension(filename) {
  const ext = filename.split(".").pop().toLowerCase();
  const map = {
    // 常见文档
    txt: "text/plain",
    csv: "text/csv",
    json: "application/json",
    pdf: "application/pdf",
    doc: "application/msword",
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    xls: "application/vnd.ms-excel",
    xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ppt: "application/vnd.ms-powerpoint",
    pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    // 图片
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    bmp: "image/bmp",
    svg: "image/svg+xml",
    // 压缩包
    zip: "application/zip",
    rar: "application/vnd.rar",
    "7z": "application/x-7z-compressed",
    // 代码
    js: "application/javascript",
    css: "text/css",
    html: "text/html",
    htm: "text/html",
    // 其它
    mp3: "audio/mpeg",
    mp4: "video/mp4",
    avi: "video/x-msvideo",
    mov: "video/quicktime",
    xml: "application/xml",
  };
  return map[ext] || "text/plain";
}
/**
 * 处理blob URL下载
 * @param {string} blobUrl - blob URL
 * @param {string} filename - 文件名
 */
async function handleBlobDownload(blobOrUrl, filename) {
  let blob;
  if (typeof blobOrUrl === 'string') {
    // 传的是 URL，fetch 获取 Blob
    const response = await fetch(blobOrUrl);
    blob = await response.blob();
  } else if (blobOrUrl instanceof Blob) {
    // 直接传的是 Blob
    blob = blobOrUrl;
  } else {
    throw new Error('参数必须是 Blob 或 URL');
  }
  // 将blob转换为array buffer
  const arrayBuffer = await blob.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  ipcRenderer.send("download-file", {
    data: buffer,
    filename: filename || "download",
    mimeType: getMimeTypeByExtension(filename),
  });
}

/**
 * 处理链接点击事件
 * @param {Event} event - 点击事件
 * @param {string} currentUrl - 当前页面URL
 */
async function handleLinkClick(event, currentUrl) {
  const target = event.target.closest("a");
  if (!target || !target.href) return;

  const url = new URL(target.href);
  const currentUrlObj = new URL(currentUrl);
  // 处理blob URL下载
  if (url.protocol === "blob:") {
    event.preventDefault();
    const filename =
      target.getAttribute("download") ||
      target.textContent.trim() ||
      "download";
    await handleBlobDownload(target.href, filename);
    return;
  }

  // 处理下载链接
  if (isDownloadLink(target.href, target)) {
    event.preventDefault();
    const filename =
      target.getAttribute("download") ||
      target.textContent.trim() ||
      "download";

    // 发送到主进程处理下载
    ipcRenderer.send("download-external-file", {
      url: target.href,
      filename: filename,
    });
    return;
  }

  // 处理外部链接
  if (
    url.hostname !== currentUrlObj.hostname ||
    url.protocol === "mailto:" ||
    url.protocol === "tel:" ||
    url.protocol === "sms:"
  ) {
    event.preventDefault();
    ipcRenderer.send("open-external-link", target.href);
    return;
  }
}

/**
 * 创建webview API对象
 * @returns {Object} webview API对象
 */
function createWebviewAPI() {
  return {
    // 发送消息到主进程
    sendToMain: (data) => ipcRenderer.send("electron-recive-message", data),
    sendToNotification: (data) =>
      ipcRenderer.send("electron-recive-notification", data),
    sendToScreenHandle: (data) =>
      ipcRenderer.send("electron-recive-screen-handle", data),
    // 监听主进程消息
    onPasteClipboard: (callback) =>
      ipcRenderer.on("electron-screenshot-paste", (_, data, bool) =>
        callback(data, bool)
      ),
    printFile: (fileUrl) => {
      ipcRenderer.send("webview-print-file", fileUrl);
    },
    sendToToggleToolbox: (data) =>
      ipcRenderer.send("electron-recive-toggle-toolbox", data),
    // 打开外部链接
    openExternalLink: (url, showDialog) => {
      ipcRenderer.send("open-external-link", url, showDialog);
    },
    // 下载文件
    downloadFile: (url, filename) => {
      ipcRenderer.send("download-external-file", { url, filename });
    },
    // 下载blob数据
    downloadBlob: (blobUrl, filename) => {
      handleBlobDownload(blobUrl, filename);
    },
    // 检查文件是否存在
    checkFileExists: (filePath) => {
      return ipcRenderer.invoke("check-file-exists", filePath);
    },
    // 打开文件位置
    openFileLocation: (filePath) => {
      ipcRenderer.send("open-file-location", filePath);
    },
  };
}

/**
 * 初始化webview事件监听
 * @param {string} currentUrl - 当前页面URL
 */
function initWebviewEventListeners(currentUrl) {
  console.log("webview-preload.js loaded");

  // 拦截所有链接点击，外部链接用系统浏览器打开
  document.addEventListener("click", async (event) => {
    await handleLinkClick(event, currentUrl);
  });
}

window.addEventListener("DOMContentLoaded", () => {
  // 初始化webview事件监听
  initWebviewEventListeners(window.location.href);
});

// 为 webview 暴露 API
contextBridge.exposeInMainWorld("webviewAPI", createWebviewAPI());
